package com.jt.demo1.proty1;

import sun.awt.HeadlessToolkit;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy {
        public static Object getProxy(Object target){
                //1.获取目标对象的类加载器
                ClassLoader classLoader = target.getClass().getClassLoader();
                //2.获取被代理者的接口
                Class<?>[] interfaces = target.getClass().getInterfaces();
               // InvocationHandler invocationHandler = getInvocationHandler(target);
                //3.利用动态代理获取对象
                InvocationHandler invocationHandler1=new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                long starTime =System.currentTimeMillis();
                                System.out.println("事物开始");
                                Object result = method.invoke(target, args);
                                System.out.println("事物结束");
                                long starTime1 =System.currentTimeMillis();
                                System.out.println(starTime1-starTime);
                                return result;
                               // return null;
                        }
                };
                return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler1);
        }
    //动态代理第一种方式
//        public static InvocationHandler getInvocationHandler (Object target){
//                return new InvocationHandler() {
//                        @Override
//                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                               long starTime =System.currentTimeMillis();
//                                System.out.println("事物开始");
//                                Object result = method.invoke(target, args);
//                                System.out.println("事物结束");
//                                long starTime1 =System.currentTimeMillis();
//                                System.out.println(starTime1-starTime);
//                                return result;
//                        }
//                };
//        }
}
